/**
 * Created with JetBrains WebStorm.
 * User: Eric
 * Date: 03/02/13
 * Time: 05:12
 * To change this template use File | Settings | File Templates.
 */
require('js-yaml');

// Get document, or throw exception on error
var translation = new Array();
var translationFiles = new Array();
var translationDir = "./translation";
var defaultLanguage = 'fr';

translationFiles['fr'] = "fr.yml";

for(var key in translationFiles){
    try {
        translation[key] = require(translationDir + "/" + translationFiles[key]);
    }catch (e) {
        console.log(e);
    }
}

var translate = function (language,toTranslate){
    if (translation[language] == undefined){
        if (translation[defaultLanguage] == undefined){
            return toTranslate;
        }
        language = defaultLanguage;
    }
    if (translation[language][toTranslate] !== undefined)
        return translation[language][toTranslate];

    return toTranslate;
}

exports.translateFormError = function translateError(form, fields){


    if (fields == null || fields.length <= 0){
        for( var field in form.fields){
            form.fields[field].error = translate("fr",form.fields[field].error);
        }
    }else{
        for(var i = 0; i < fields.length; i++){
            if (form.fields[fields[i]] !== undefined){
                form.fields[fields[i]].error = translate("fr",form.fields[fields[i]].error);
            }
        }
    }
}

exports.translate = translate;